package org.ysu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.ysu.mapper.*;
import org.ysu.pojo.*;
import org.ysu.service.ClueService;

import org.springframework.stereotype.Service;
import org.ysu.mapper.ClueMapper;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * @author libaoyu
 * @description 针对表【clue】的数据库操作Service实现
 * @createDate 2024-06-17 14:59:53
 */
@Service
public class ClueServiceImpl extends ServiceImpl<ClueMapper, Clue> implements ClueService{
    @Resource
    private ClueMapper clueMapper;
    @Resource
    private PoorMapper poorMapper;
    @Resource
    private VCadreMapper vCadreMapper;
    @Autowired
    private InterviewMapper interviewMapper;
    @Autowired
    private FamilyMapper familyMapper;
    @Autowired
    private CCadreMapper cCadreMapper;


    @Override
    public Integer insertClue(Clue clue) {

        if (clue == null) {
            throw new IllegalArgumentException("Clue对象不能为空");
        }
        try {
            clueMapper.insertClue(clue);
            return clue.getId(); // 正确的返回关键字
        } catch (Exception e) {
            //LOGGER.error("插入Clue时发生异常", e);
            // 根据实际情况，可以选择抛出自定义异常或者返回特定的错误信息
            throw new RuntimeException("插入Clue失败", e);
        }
    }

    @Override
    public List<Clue> getListsByCcid(Integer id) {

        return clueMapper.getListsByCcid(id);
    }

    @Override
    public Integer changeRisk(Integer id, Integer riskFinance, Integer riskSocial, Integer riskMan, Integer riskSubstance, Integer riskNature, Date updateTime) {

        System.out.println(clueMapper.changeRisk(id, riskFinance, riskSocial, riskMan, riskSubstance, riskNature,  updateTime));
        if (clueMapper.changeRisk(id, riskFinance, riskSocial, riskMan, riskSubstance, riskNature,updateTime) != 0){
              return 1;
          }
        else return 0;
    }


    /**
     * 核实员id查线索
     * @param vid
     * @return
     */
    @Override
    public List<ClueAndPName> getClueByvId(Integer vid) {
        LambdaQueryWrapper<Clue> wrapper = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<Poor> pw = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<CCadre> cw = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<Family> fw = new LambdaQueryWrapper<>();
        //查询全部
        wrapper.eq(Clue::getVId, vid).eq(Clue::getStatus, 0)
                .or()
                .eq(Clue::getVId, vid).eq(Clue::getStatus, 1);
        List<Clue> clues = clueMapper.selectList(wrapper);
        List<ClueAndPName> clueAndPNames = new ArrayList<>();
        for (Clue clue : clues) {
            ClueAndPName clueAndPName = new ClueAndPName();
            clueAndPName.setId(clue.getId());
            clueAndPName.setCcId(clue.getCcId());
            clueAndPName.setFId(clue.getFId());
            clueAndPName.setPId(clue.getPId());
            clueAndPName.setVId(clue.getVId());
            clueAndPName.setDetail(clue.getDetail());
            clueAndPName.setRiskFinance(clue.getRiskFinance());
            clueAndPName.setRiskMan(clue.getRiskMan());
            clueAndPName.setRiskNature(clue.getRiskNature());
            clueAndPName.setRiskSocial(clue.getRiskSocial());
            clueAndPName.setRiskSubstance(clue.getRiskSubstance());
            clueAndPName.setStatus(clue.getStatus());
            clueAndPName.setCreateTime(clue.getCreateTime());
            clueAndPName.setUpdateTime(clue.getUpdateTime());
            int pid= clue.getPId();
            pw.eq(Poor::getPId, pid);
            Poor poor = poorMapper.selectOne(pw);
            clueAndPName.setAvatar(poor.getAvator());
            pw.clear();
            int cid = clue.getCcId();
            clueAndPName.setPName(poor.getName());
            clueAndPName.setPhone(poor.getPhone());
            fw.eq(Family::getFId, poor.getFId());
            Family family= familyMapper.selectOne(fw);
            fw.clear();
            clueAndPName.setAddress(family.getProvince()+family.getCity()+family.getCountry()+family.getTownship()+family.getVillage());
            cw.eq(CCadre::getCcId, cid);
            CCadre cCadre = cCadreMapper.selectOne(cw);
            cw.clear();
            clueAndPName.setCcName(cCadre.getName());
            clueAndPNames.add(clueAndPName);

        }
        return clueAndPNames;
    }

    @Override
    public Statistics getRiskData(Integer id,Integer data) {
        // 获取当前日期
        Date endDate = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String endTime = dateFormat.format(endDate);

        // 使用 Calendar 进行日期减法
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(endDate);
        calendar.add(Calendar.DAY_OF_MONTH, -data + 1);
        Date startDate = calendar.getTime();
        String startTime = dateFormat.format(startDate);
        Integer STATUS_SUCCESS=1;

//        计算天数
        Statistics statistics=new Statistics();

        LambdaQueryWrapper<Clue> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(Clue::getFId,id)
                .eq(Clue::getStatus,STATUS_SUCCESS)
                .between(Clue::getCreateTime,startTime+" 00:00:00",endTime+" 23:59:59")
                .orderByAsc(Clue::getCreateTime);
        List<Clue> clues = clueMapper.selectList(wrapper);

        // 统计每个风险每次的变化情况
        // 0:man;1:substance;2:social;3:nature;4:finance
        Map<Integer, Map<String, Integer>> records = new HashMap<>();
        for(int i=0;i<5;i++){
            records.put(i, new HashMap<>());
        }
        Map<String, Integer> dateRange1 = new HashMap<>();
        for (Clue clue : clues) {
            Date interviewDate = clue.getCreateTime(); // 获取记录的日期
            String interviewDate1 = dateFormat.format(interviewDate); //转格式
            if(dateRange1.containsKey(interviewDate1)){
                continue;
            }
            int man = clue.getRiskMan(); // 获取记录的人员ID
            int sub=clue.getRiskSubstance();
            int social=clue.getRiskSocial();
            int nature=clue.getRiskNature();
            int finance=clue.getRiskFinance();
            // 更新hash表数据
            for(int i=0;i<5;i++){
                switch (i){
                    case 0:
                        records.get(i).put(interviewDate1,man);
                        break;
                    case 1:
                        records.get(i).put(interviewDate1,sub);
                        break;
                    case 2:
                        records.get(i).put(interviewDate1,social);
                        break;
                    case 3:
                        records.get(i).put(interviewDate1,nature);
                        break;
                    case 4:
                        records.get(i).put(interviewDate1,finance);
                        break;
                    default:
                        break;
                    }
            }
            dateRange1.put(interviewDate1,1);
        }
        // 将结果整理为二维数组
        List<String> names = new ArrayList<>();
        names.add("人力");
        names.add("物资");
        names.add("社会");
        names.add("自然");
        names.add("经济");
        List<Date> dateRange = new ArrayList<>();
        for (int i = 0; i < data; i++) {
            Date date = calendar.getTime();
            dateRange.add(date);
            calendar.add(Calendar.DAY_OF_MONTH, +1);
        }
        Integer[][] counts = new Integer[records.size()][data];

        int personIndex = 0;
        for (Map.Entry<Integer, Map<String, Integer>> entry : records.entrySet()) {

            Map<String, Integer> record2 = entry.getValue();

            int dateIndex = 0;
            for (Date date : dateRange) {
                String dateString = dateFormat.format(date);
                counts[personIndex][dateIndex] = 0;
                if(record2.get(dateString)!=null){
                    counts[personIndex][dateIndex] = record2.get(dateString);
                }
                dateIndex++;
            }
            personIndex++;
        }
        statistics.setNames(names);
        statistics.setCounts(counts);
        return statistics;
    }

    @Override
    public List<Clue> getListsByVid(Integer vid) {
        LambdaQueryWrapper<Clue> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Clue::getVId, vid);
        List<Clue> clues = clueMapper.selectList(wrapper);
        return clues;
    }
}




